/*
 * @Author       : lg
 * @Date         : 2022-06-24 22:48:08
 * @LastEditors  : lg
 * @LastEditTime : 2022-06-24 22:57:39
 * @FilePath     : \TwoWeeksFaceTest\ws-server\server\ws.p2p.js
 * @description  :
 */
// 获得服务的类
const { WebSocketServer } = require("ws");
// 创建实例
const wsServer = new WebSocketServer({ port: 3000 });
// 保存多个窗口client的ws连接
const list = new Set();
// 监听连接事件
wsServer.on("connection", curWs => {
  // 连接成功
  console.info("connected");
  // 不能一直add，实际使用中需要一些清理缓存的机制，长期用不到的ws要被delete
  list.add(curWs);
  curWs.on("message", msg => {
    const rawData = JSON.parse(msg.toString());
    console.info("recived message", rawData);
    rawData.data = Number(rawData.data) + 1;
    rawData.msg = "更新成功！";
    rawData.code = 200;
    // 传递给其他客户端
    list.forEach(ws => {
      if (curWs !== ws) {
        ws.send(JSON.stringify(rawData));
      }
    });
  });
});
